import { Sprite, Texture } from 'pixi.js';
import { Body, Bodies, World } from 'matter-js';
import { Entity, EntityConfig } from './Entity';

export interface PlayerConfig extends EntityConfig {
  speed?: number;
  dashSpeed?: number;
  dashDuration?: number;
  dashCooldown?: number;
}

export class Player extends Entity {
  private speed: number;
  private dashSpeed: number;
  private dashDuration: number;
  private dashCooldown: number;
  private isDashing: boolean;
  private dashTimer: number;
  private dashCooldownTimer: number;
  private movement: { x: number; y: number };
  private isInvulnerable: boolean;

  constructor(config: PlayerConfig) {
    super(config);
    
    // 初始化移动相关属性
    this.speed = config.speed || 5;
    this.dashSpeed = config.dashSpeed || 15;
    this.dashDuration = config.dashDuration || 150; // 毫秒
    this.dashCooldown = config.dashCooldown || 1000; // 毫秒
    
    // 状态标志
    this.isDashing = false;
    this.dashTimer = 0;
    this.dashCooldownTimer = 0;
    this.isInvulnerable = false;
    
    // 移动向量
    this.movement = { x: 0, y: 0 };
    
    // 添加玩家标签
    this.addTag('player');
  }

  // 处理移动输入
  public handleMovement(keys: Set<string>): void {
    // 重置移动向量
    this.movement.x = 0;
    this.movement.y = 0;

    // 处理WASD或方向键输入
    if (keys.has('KeyW') || keys.has('ArrowUp')) this.movement.y = -1;
    if (keys.has('KeyS') || keys.has('ArrowDown')) this.movement.y = 1;
    if (keys.has('KeyA') || keys.has('ArrowLeft')) this.movement.x = -1;
    if (keys.has('KeyD') || keys.has('ArrowRight')) this.movement.x = 1;

    // 对角线移动时归一化向量
    if (this.movement.x !== 0 && this.movement.y !== 0) {
      const length = Math.sqrt(this.movement.x * this.movement.x + this.movement.y * this.movement.y);
      this.movement.x /= length;
      this.movement.y /= length;
    }
  }

  // 触发冲刺
  public dash(): void {
    if (!this.isDashing && this.dashCooldownTimer <= 0) {
      this.isDashing = true;
      this.isInvulnerable = true;
      this.dashTimer = this.dashDuration;
      this.dashCooldownTimer = this.dashCooldown;
    }
  }

  // 更新玩家状态
  public update(delta: number): void {
    // 更新冲刺状态
    if (this.isDashing) {
      this.dashTimer -= delta;
      if (this.dashTimer <= 0) {
        this.isDashing = false;
        this.isInvulnerable = false;
      }
    }

    // 更新冲刺冷却
    if (this.dashCooldownTimer > 0) {
      this.dashCooldownTimer -= delta;
    }

    // 计算当前速度
    const currentSpeed = this.isDashing ? this.dashSpeed : this.speed;

    // 更新位置
    const newX = this.x + this.movement.x * currentSpeed;
    const newY = this.y + this.movement.y * currentSpeed;
    this.setPosition(newX, newY);
  }

  // 检查是否处于无敌状态
  public isInvulnerableState(): boolean {
    return this.isInvulnerable;
  }

  // 销毁实例
  public destroy(): void {
    if (this.sprite && !this.sprite.destroyed) {
      this.sprite.destroy();
    }
    if (this.body && this.body.world) {
      World.remove(this.body.world, this.body);
    }
  }
}